<template>
  <div class="wrapper">
    <el-form :model="formItem" :rules="rules" ref="formRef" :label-width="80">
      <el-form-item label="姓名" prop="realName">
        <el-input class="wrapper-user-name" v-model="formItem.realName" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="formItem.gender" type="button" button-style="solid">
          <el-radio value="F" label="男"></el-radio>
          <el-radio value="M" label="女"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input type="number" class="wrapper-user-name" v-model="formItem.age" placeholder="请输入年龄" />
      </el-form-item>
      <el-form-item label="擅长领域" prop="domain">
        <el-input class="wrapper-user-name" v-model="formItem.domain" placeholder="请输入擅长领域" />
      </el-form-item>
      <el-form-item label="过往经验" prop="resume">
        <el-input type="textarea" class="wrapper-user-name" :autosize="{ minRows: 9 }" v-model="formItem.resume" placeholder="请输入过往经验" />
      </el-form-item>
      <el-form-item label="展示图片">
<!--        <img alt="formItem.realName" :src="formItem.pic" style="width: 300px;height: 300px;object-fit:cover" />-->
<!--        <br />-->
        <el-upload ref='upload' :before-upload='beforeAvatarUpload' :on-success='handleSuccess' v-model:file-list="fileList"
                   :action="action" list-type="picture-card" :auto-upload="true" :limit='1' :on-exceed='handleExceed'>
          <el-icon><Plus /></el-icon>

          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="imgUrl"  style='height: 100%;' alt="" />
              <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
            </div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang='ts'>
import storage from '@/utils/storage.ts';
import { updateUser } from '@/api/sys/user'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type UploadInstance, type UploadProps, type UploadRawFile } from 'element-plus'
import { Plus,ZoomIn,Delete } from '@element-plus/icons-vue'
import { getCoachForm, updateCoach } from '@/api/coach'

const formRef = ref()
const rules = reactive({ // 验证规则
  nickName: [{required: true, message: '请填写昵称'},
    { max: 16, message: '昵称最多允许输入16位'}]
})
const user = ref({})
const coach = ref({})
const imgUrl = ref('')
const imgPath = ref('')
const formItem = reactive({
  realName: undefined,
  gender: undefined,
  age: undefined,
  domain: undefined,
  resume: undefined,
  pic: undefined,
}) // 表单数据
const action = ref('/dev/api/v1/common/upload') // 上传接口
const token = reactive({
  'Authorization': ''
}) // 验证token
const fileList = reactive([])
function save () { // 保存
  formRef.value.validate(valid => {
    if (valid) {
      let params = {
        age: formItem.age,
        domain: formItem.domain,
        resume: formItem.resume,
        userId: user.value.id,
        pic: imgUrl.value,
        realName: formItem.realName,
        gender: formItem.gender,
      }
      updateCoach(params).then(res => {
        if (res.code === '00000') {
          ElMessage.success('修改成功')
        }
      })
    }
  })
}
const fileLst = ref([])
const disabled = ref(false)
const dialogImageUrl = ref()
const dialogVisible = ref()
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('只能上传jpg格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('图片不能大于1MB!')
    return false
  }
  return true
}
const handleSuccess = (res,file)=>{
  if(res.code === '00000'){
    imgUrl.value = res.data
    imgPath.value = res.data
    formItem.avatar = imgUrl.value
  }
}
const handleRemove: UploadProps['onRemove'] = (uploadFile) => {
  console.log(uploadFile)
  uploadFile.url = ''
  imgUrl.value = ''
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = new Date().valueOf();
  upload.value!.handleStart(file)
}
// function handleSuccess (res, file) { // 上传成功
//   this.$set(this.formItem, 'face', res.result)
// }

onMounted(()=>{
  user.value = JSON.parse(storage.getItem('user'))
  getCoachForm(user.value.id).then((resp)=>{
    coach.value = resp.data
    Object.assign(formItem,coach.value)
    console.log('url',coach.value.pic,'realName:',coach.value.realName)
    fileLst.value = []
    fileLst.value.push([{url: coach.value.pic,name: coach.value.realName}])
    imgUrl.value = coach.value.pic
  })

  token.Authorization = storage.getItem('accessToken');
})
</script>

<style scoped>

</style>
